package com.snail.service.Impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.snail.model.entity.Product;
import com.snail.model.entity.User;
import com.snail.model.pojo.SearchHitResult;
import com.snail.service.BizUserService;
import com.snail.service.HotdataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author cici
 * @description user
 * @date 2025/8/19 17:10
 */
@Service
public class BizUserServiceImpl implements BizUserService {
    @Autowired
    HotdataService hotdataService;
    @Autowired
    private ElasticsearchClient elasticsearchClient;
    @Override
    public SearchResponse<User> searchProductsByClient(String keyword, int page, int size) {
        try {
            return elasticsearchClient.search(s -> s
                            .index("sys_user")
                            .query(q -> q
                                    .bool(b -> b
                                            // must 里面放 multiMatch：匹配 keyword
                                            .must(m -> m
                                                    .multiMatch(mm -> mm
                                                            .fields("username", "nickname", "email", "phone")
                                                            .query(keyword)
                                                    )
                                            )
                                    )
                            ).from((page - 1) * size) // 起始位置 (offset)
                            .size(size),              // 每页条数,
                    User.class // 指定返回的文档类型
            );
        } catch (IOException e) {
            throw new RuntimeException("搜索失败", e);
        }
    }

    @Override
    public SearchHitResult<User> searchAndSerialize(String keyword, int page, int size) {
        SearchHitResult<User> res=SearchHitResult.<User>fromSearchHits( this.searchProductsByClient(keyword,page,size));
        return res;
    }

    @Override
    public SearchHitResult<User> SearchAsHot(String keyword, int page, int size) {
        return hotdataService.queryHotData(keyword+"&page:"+page+"&size:"+size,(Class<SearchHitResult<User>>) (Class<?>) SearchHitResult.class,
                k -> this.searchAndSerialize(k, page, size)) ; // 把 page/size 固定住;
    }
}
